package com.wlb365.financing.modules.credit.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.wlb365.financing.common.constants.ApiConstants;
import com.wlb365.financing.common.constants.SysConstant;
import com.wlb365.financing.common.dto.R;
import com.wlb365.financing.common.exception.AdminException;
import com.wlb365.financing.common.utils.SdkHelper;
import com.wlb365.financing.common.utils.ShiroUtil;
import com.wlb365.financing.common.utils.StringUtils;
import com.wlb365.financing.modules.credit.request.ApplyAuditReq;
import com.wlb365.financing.modules.credit.request.CreditAuditInfoReq;
import com.wlb365.financing.modules.credit.request.CreditCoreBankInfoReq;
import com.wlb365.financing.modules.credit.request.CreditCoreBankReq;
import com.wlb365.financing.modules.credit.request.CreditDataReq;
import com.wlb365.financing.modules.credit.request.CreditInfoQueryPageReq;
import com.wlb365.financing.modules.credit.request.CreditInfoUpdateReq;
import com.wlb365.financing.modules.credit.request.CreditTradePageDataReq;
import com.wlb365.financing.modules.credit.request.CreditUseRecordsAddReq;
import com.wlb365.financing.modules.credit.request.CreditUseRecordsQueryPageReq;
import com.wlb365.financing.modules.credit.request.SupplierBankDataReq;
import com.wlb365.financing.modules.credit.response.CreditAuditInfoVo;
import com.wlb365.financing.modules.credit.response.CreditCoreBankInfoVo;
import com.wlb365.financing.modules.credit.response.CreditCoreBankVo;
import com.wlb365.financing.modules.credit.response.CreditDataVo;
import com.wlb365.financing.modules.credit.response.CreditInfoPageVo;
import com.wlb365.financing.modules.credit.response.CreditTradePageDataVo;
import com.wlb365.financing.modules.credit.response.CreditUseRecordsAddVo;
import com.wlb365.financing.modules.credit.response.CreditUseRecordsQueryPageVo;
import com.wlb365.financing.modules.credit.response.OrgRelationVo;
import com.wlb365.financing.modules.orgaccount.response.OrgAccountRes;
import com.wlb365.financing.modules.sys.entity.User;
import com.wlb365.sdk.client.SdkClient;
import com.wlb365.sdk.model.CommonRequest;
import com.wlb365.sdk.model.CommonResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 授信
 * @Author LuHang
 * @Date 2021/4/21 9:43
 * @Version 1.0
 */
@RestController
@RequestMapping("credit")
public class CreditController {

    @Autowired
    private SdkClient sdkClient;

    /**
     * 新增额度详情视图
     * @param compId
     * @param bankId
     * @param financingId
     * @return
     */
    @RequiresPermissions("credit:use:add")
    @GetMapping(value = "use/addView")
    public ModelAndView addUseView(String compId,String bankId,String financingId){
        ModelAndView modelAndView = new ModelAndView("credit/credit_use_edit");
        modelAndView.addObject("compId",compId);
        modelAndView.addObject("bankId",bankId);
        return modelAndView;
    }

    /**
     * 额度详情管理
     * @return
     */
    @RequiresPermissions("credit:applyInfo:index")
    @GetMapping(value = "applyInfo/index")
    public ModelAndView applyInfoView(){
        ModelAndView modelAndView = new ModelAndView("credit/credit_apply_info");
        return modelAndView;
    }

    /**
     * 填写额度页面
     * @param id
     * @return
     */
    @RequiresPermissions("credit:info:edit")
    @GetMapping(value = "info/edit")
    public ModelAndView edit(String id){
        ModelAndView modelAndView = new ModelAndView("credit/credit_info_edit");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    /**
     * 额度使用详情页面
     * @return
     */
    @RequiresPermissions("credit:use:index")
    @GetMapping(value = "use/index")
    public ModelAndView userIndex(){
        ModelAndView modelAndView = new ModelAndView("credit/credit_use_info");
        return modelAndView;
    }

    /**
     * 授信额度页面
     * @return
     */
    @RequiresPermissions("credit:info:index")
    @GetMapping(value = "info/index")
    public ModelAndView infoIndex(){
        ModelAndView modelAndView = new ModelAndView("credit/credit_info");
        return modelAndView;
    }

    /**
     * 交易记录界面
     * @param supplierId 供应商id
     * @return
     */
    @RequiresPermissions("credit:trade:index")
    @GetMapping(value = "trade/index")
    public ModelAndView tradeIndex(@RequestParam(name = "supplierId") String supplierId){
        ModelAndView modelAndView = new ModelAndView("credit/credit_trade");
        modelAndView.addObject("supplierId",supplierId);
        return modelAndView;
    }

    /**
     * 查询供应商基本信息
     *
     * @return
     */
    @RequiresPermissions("credit:bank:info")
    @GetMapping("bank/info")
    public R bankInfo(CreditCoreBankInfoReq creditCoreBankInfoReq) {

        // 查询供应商基本信息
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_ONE);
        Map<String, Object> params = new HashMap<>();
        params.put("id", ShiroUtil.getUser().getDeptId());
        commonRequest.setBizModel(params);
        CommonResponse response = null;
        response = sdkClient.execute(commonRequest);
        CreditCoreBankInfoVo orgInfo = JSONUtil.toBean(response.getData(), CreditCoreBankInfoVo.class);

        ModelAndView modelAndView = new ModelAndView("credit/credit_bank_info");

        modelAndView.addObject("supplierId", ShiroUtil.getUser().getDeptId());
        modelAndView.addObject("bankId", creditCoreBankInfoReq.getId());
        modelAndView.addObject("creditCoreBankInfo", orgInfo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("supplierId",ShiroUtil.getUser().getDeptId());
        jsonObject.put("bankId", creditCoreBankInfoReq.getId());
        jsonObject.put("creditCoreBankInfo", orgInfo);
        return R.ok(jsonObject);
    }

    /**
     * 授信匹配关系界面
     * @returncredit:bank:info
     */
    @RequiresPermissions("credit:bank:index")
    @GetMapping("bank/index")
    public ModelAndView bankIndex() {

        return new ModelAndView("credit/credit_bank");
    }

    /**
     * 根据银行机构id查询与核心企业关联关系
     */
    @RequiresPermissions("credit:matched:list")
    @GetMapping("matched/list/data")
    public JSONObject supplierBankList(SupplierBankDataReq supplierBankDataReq){
        // 查询银行与核心企业关联关系
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_QUERY_RELATIONS);
        Map<String,Object> params = new HashMap<>();
        params.put("compId", supplierBankDataReq.getCompId());
        params.put("type", 1);
        commonRequest.setBizModel(params);
        CommonResponse response = sdkClient.execute(commonRequest);
        JSONObject jsonObject = JSONObject.parseObject(response.getData());
        return jsonObject;
    }

    /**
     * 授信审核页面
     * @return
     */
    @RequiresPermissions("credit:audit:index")
    @GetMapping("audit/index")
    public ModelAndView index() {
        return new ModelAndView("credit/credit");
    }

    /**
     * 申请授信列表页面
     * @return
     */
    @RequiresPermissions("credit:apply:index")
    @GetMapping("apply/index")
    public ModelAndView applyIndex() {
        return new ModelAndView("credit/credit_apply");
    }

    /**
     * 授信申请弹出框
     * @return
     */
    @GetMapping("creditApplicationLayer")
    public ModelAndView creditApplicationLayer() {
        return new ModelAndView("credit/credit_application_layer");
    }



    /**
     * 查询单条授信信息(供应商信息)
     * @param supplierId 供应商id
     * @param auditId 主键id
     * @param type 1 详情 2 审核
     * @param status 审核状态
     * @return
     */
    @RequiresPermissions("credit:audit:audit")
    @GetMapping("auditView")
    public ModelAndView auditView(String supplierId,int type,String auditId,String status) {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_ONE);
        Map<String,Object> params = new HashMap<>();
        params.put("id", supplierId);
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        CreditCoreBankInfoVo creditCoreBankInfoVo = JSONUtil.toBean(commonResponse.getData(),CreditCoreBankInfoVo.class);
        ModelAndView modelAndView = new ModelAndView("credit/credit_audit");
        modelAndView.addObject("supplierId",supplierId);
        modelAndView.addObject("auditId",auditId);
        modelAndView.addObject("type",type);
        modelAndView.addObject("status",status);
        modelAndView.addObject("creditCoreBankInfo",creditCoreBankInfoVo);
        commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_AUDIT_ONE);
        params = new HashMap<>();
        params.put("id",auditId);
        commonRequest.setBizModel(params);
        commonResponse =  sdkClient.execute(commonRequest);
        CreditAuditInfoVo creditAuditInfoVo = JSONUtil.toBean(commonResponse.getData(),CreditAuditInfoVo.class);
        modelAndView.addObject("creditAuditInfoVo",creditAuditInfoVo);
        modelAndView.addObject("remark",creditAuditInfoVo.getRemark());
        return modelAndView;
    }

    /**
     * 授信审核
     * @return
     */
    @PostMapping(value = "audit")
    public R audit(CreditAuditInfoReq creditAuditReq){

        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_AUDIT_CREDIT);
        Map<String,Object> params = new HashMap<>();
        params.put("audiCompId", ShiroUtil.getUser().getDeptId());
        params.put("auditId", creditAuditReq.getAuditId());
        params.put("remark",creditAuditReq.getRemark());
        params.put("createBy",ShiroUtil.getUser().getUsername());
        String status = creditAuditReq.getStatus();
        if(status.equals("1")){
            User user = ShiroUtil.getUser();
            // 9 代表平台
            if(user.getDept().getType().equals(9)){
                status = "1";
            }else{
                status = "4";
            }
        }
        // 审核拒绝
        else if(status.equals("2")){
            // 9 代表平台
            if(ShiroUtil.getUser().getDept().getType().equals(9)){
                status = "2";
            }else{
                status = "5";
            }
        }
        params.put("status",status);
        params.put("supplierId",creditAuditReq.getSupplierId());
        params.put("supplierId",creditAuditReq.getSupplierId());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        if(!commonResponse.getCode().equals(ApiConstants.SUCCESS_CODE)){
            throw new AdminException("服务端异常,授信审核失败");
        }
        return R.ok();
    }

    /**
     * 授信申请（审核）列表查询
     * @return
     */
    @GetMapping(value = "list/data")
    public CreditDataVo list(CreditDataReq creditAuditReq){
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_AUDIT_PAGE);
        Map<String,Object> params = new HashMap<>();
        String compId = creditAuditReq.getCompId();
        // 不是平台管理员就查询与自己相关的
        if(!ShiroUtil.getUser().getUsername().equals(SysConstant.ADMIN)){
            compId = ShiroUtil.getUser().getDept().getId();
        }
        params.put("compId",compId);
        params.put("current",creditAuditReq.getCurrent());
        params.put("size",creditAuditReq.getSize());
        params.put("status",creditAuditReq.getStatus());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        CreditDataVo creditAuditVo = JSONUtil.toBean(commonResponse.getData(), CreditDataVo.class);
        return creditAuditVo;
    }

    /**
     * 查询核心机构与银行匹配关系
     * @return
     */
    @GetMapping(value = "list/coreBankRelations")
    public JSONObject coreBankRelations(CreditCoreBankReq creditCoreBankReq){
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_CORE_BANK_RELATIONS);
        Map<String,Object> params = new HashMap<>();
        params.put("compId",creditCoreBankReq.getCompId());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        JSONObject jsonObject = JSONObject.parseObject(commonResponse.getData());
        return jsonObject;
    }

    /**
     * 查询历史交易列表
     * @return
     */
    @GetMapping(value = "trade/list/data")
    public CreditTradePageDataVo tradeListData(CreditTradePageDataReq creditTradePageDataReq) throws ParseException {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_QUERY_TRADE_PAGE);
        Map<String,Object> params = new HashMap<>();
        params.put("beginTradeDate",creditTradePageDataReq.getBeginTradeDate() !=null ? creditTradePageDataReq.getBeginTradeDate().replace("-",""):null);
        params.put("contractNo",creditTradePageDataReq.getContractNo());
        params.put("coreEnterpriseId",creditTradePageDataReq.getCoreEnterpriseId());
        params.put("current",creditTradePageDataReq.getCurrent());
        params.put("endTradeDate",creditTradePageDataReq.getEndTradeDate() !=null ? creditTradePageDataReq.getEndTradeDate().replace("-",""):null);
        params.put("id",creditTradePageDataReq.getId());
        params.put("projectCode",creditTradePageDataReq.getProjectCode());
        params.put("projectName",creditTradePageDataReq.getProjectName());
        params.put("size",creditTradePageDataReq.getSize());
        params.put("supplierId",creditTradePageDataReq.getSupplierId());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        CreditTradePageDataVo creditTradePageDataVo = JSONUtil.toBean(commonResponse.getData(),CreditTradePageDataVo.class);
        return creditTradePageDataVo;
    }

    /**
     * 申请授信
     *
     * @return
     */
    @PostMapping(value = "applyAudit")
    public R applyAudit(ApplyAuditReq req) {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_APPLY_CREDIT);
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> supplyMap = new HashMap<>();
        params.put("supplierId", req.getSupplierId());
        params.put("bankId", req.getBankId());
        params.put("applyAmount", req.getApplyAmount());
        params.put("id", req.getSupplierId());
        params.put("compName", req.getCompName());
        params.put("supplierType", req.getSupplierType());
        params.put("comCerNo", req.getComCerNo());
        params.put("comAddress", req.getComAddress());
        params.put("admName", req.getAdmName());
        params.put("admMobPhone", req.getAdmMobPhone());
        params.put("admCerNo", req.getAdmCerNo());
        params.put("registrationNo", req.getRegistrationNo());
        if(StrUtil.isNotEmpty(req.getSetupDate())){
            params.put("setupDate",req.getSetupDate().replace("-","") );
        }
        params.put("registryAmount", req.getRegistryAmount());
        params.put("bankNo", req.getBankNo());
        params.put("legalName", req.getLegalName());
        params.put("legalNo", req.getLegalNo());
        params.put("businessScope", req.getBusinessScope());
        params.put("payrolls", req.getPayrolls());
        params.put("businessTotalAmount", req.getBusinessTotalAmount());
        params.put("businessSalesAmount", req.getBusinessSalesAmount());
        params.put("supplierInfo", supplyMap);
        commonRequest.setBizModel(params);
        CommonResponse commonResponse = sdkClient.execute(commonRequest);
        if (!commonResponse.getCode().equals(ApiConstants.SUCCESS_CODE)) {
            return R.fail(commonResponse.getMsg());
        }
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(commonResponse.getData());
        if (!"1".equals(jsonObject.getStr("status"))) {
            return R.fail(jsonObject.getStr("error"));
        }
        return R.ok();
    }

    /**
     * 授信额度列表查询
     *
     * @return
     */
    @GetMapping(value = "info/listData")
    public CreditInfoPageVo listData(CreditInfoQueryPageReq creditInfoQueryPageReq) {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_QUERY_INFO_PAGE);
        Map<String,Object> params = new HashMap<>();
        params.put("current",creditInfoQueryPageReq.getCurrent());
        params.put("size",creditInfoQueryPageReq.getSize());
        params.put("compId",creditInfoQueryPageReq.getCompId());
        params.put("bankId",creditInfoQueryPageReq.getBankId());
        params.put("status",creditInfoQueryPageReq.getStatus());
        params.put("applyAmountStart",creditInfoQueryPageReq.getApplyAmountStart());
        params.put("applyAmountEnd",creditInfoQueryPageReq.getApplyAmountEnd());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        CreditInfoPageVo creditInfoPageVo = JSONUtil.toBean(commonResponse.getData(), CreditInfoPageVo.class);
        return creditInfoPageVo;
    }

    /**
     * 额度使用详情列表查询
     *
     * @return
     */
    @GetMapping(value = "use/listData")
    public CreditUseRecordsQueryPageVo UseListData(CreditUseRecordsQueryPageReq creditUseRecordsQueryPageReq) throws ParseException {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_QUERY_USE_PAGE);
        Map<String,Object> params = new HashMap<>();
        params.put("current",creditUseRecordsQueryPageReq.getCurrent());
        params.put("size",creditUseRecordsQueryPageReq.getSize());
        params.put("compId",creditUseRecordsQueryPageReq.getCompId());
        params.put("applyAmountStart",creditUseRecordsQueryPageReq.getApplyAmountStart());
        params.put("applyAmountEnd",creditUseRecordsQueryPageReq.getApplyAmountEnd());
        if(!StringUtils.isEmpty(creditUseRecordsQueryPageReq.getUseDate())){
            params.put("useDate",creditUseRecordsQueryPageReq.getUseDate());
        }
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        CreditUseRecordsQueryPageVo creditUseRecordsQueryPageVo = JSONUtil.toBean(commonResponse.getData(), CreditUseRecordsQueryPageVo.class);
        return creditUseRecordsQueryPageVo;
    }

    /**
     * 查询核心机构与银行匹配关系
     * @return
     */
    @PostMapping(value = "info/update")
    public R infoUpdate(CreditInfoUpdateReq creditInfoUpdateReq){
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_UPDATE_INFO);
        Map<String,Object> params = new HashMap<>();
        params.put("id",creditInfoUpdateReq.getId());
        params.put("amount",creditInfoUpdateReq.getAmount());
        params.put("status","1");
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        return R.ok();
    }

    /**
     * 新增额度详情
     * @return
     */
    @PostMapping(value = "use/add")
    public R userAdd(CreditUseRecordsAddReq creditUseRecordsAddReq) throws ParseException {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CREDIT_ADD_USE_RECORDS);
        Map<String,Object> params = new HashMap<>();
        params.put("compId",creditUseRecordsAddReq.getCompId());
        params.put("bankId",creditUseRecordsAddReq.getBankId());
        params.put("financingId",creditUseRecordsAddReq.getFinancingId());
        params.put("type",creditUseRecordsAddReq.getType());
        params.put("amount",creditUseRecordsAddReq.getAmount());
        params.put("beforAmount",creditUseRecordsAddReq.getBeforAmount());
        params.put("afterAmount",creditUseRecordsAddReq.getAfterAmount());
        params.put("acctNo",creditUseRecordsAddReq.getAcctNo());
        params.put("remark",creditUseRecordsAddReq.getRemark());
        params.put("useDate",new SimpleDateFormat("yyyy-MM-dd").parse(creditUseRecordsAddReq.getUseDate()));
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        CreditUseRecordsAddVo creditUseRecordsAddVo = JSONUtil.toBean(commonResponse.getData(),CreditUseRecordsAddVo.class);
        if (null != creditUseRecordsAddVo.getError()) {
            commonResponse.setMsg(creditUseRecordsAddVo.getError());
            return R.fail(commonResponse.getMsg());
        }
        return R.ok();
    }


}
